package com.scau.hwadee.examination.config.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author YHX
 * @date 2019/8/4 10:42
 * description
 */
@Slf4j
public class SessionFilter extends AccessControlFilter {

  private static final String[] NOT_FILTERS = {"account", "index", "static", "favicon", "csrf", "webjars", "swagger", "v2/api-docs"};

  @Override
  protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
    return false;
  }

  @Override
  protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
//        String url = request.getRequestURL().toString();
    String uri = request.getRequestURI();
//        log.debug("当前请求的URL为：" + url);
    log.debug("当前请求的URI为：" + uri);
    Subject subject = SecurityUtils.getSubject();
    Session session = subject.getSession();
    Object isReLogin = session.getAttribute("isReLogin");
//    if (subject == null || subject.getPrincipal() == null || !subject.isAuthenticated()) {
    if (isReLogin != null && (boolean) isReLogin) {
      boolean isRedirect = true;
      for (String notFilter : NOT_FILTERS) {
        if (uri.contains(notFilter) || "/".equals(uri)) {
          isRedirect = false;
          break;
        }
      }
      if (isRedirect) {
        log.debug("发生重定向");
        WebUtils.getAndClearSavedRequest(servletRequest);
//        WebUtils.redirectToSavedRequest(servletRequest, servletResponse, "/index.html");
        WebUtils.issueRedirect(servletRequest,servletResponse,"/account/index");
        return false;
      }
    }
    return true;
  }
}
